package com.none.web.service.comments.impl;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.DateUtil;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.model.TUser;
import com.none.web.model.TComments;
import com.none.web.model.TUserApp;
import com.none.web.service.comments.ICommentsService;

/**
 * 
 * @Description: 评论管理Service实现
 * @author Bing
 * @date 2015年6月25日 上午10:28:53
 */
@Service("commentService")
public class CommentsServiceImpl extends BaseServiceSupport implements ICommentsService {
	@Autowired
    JdbcTemplate jdbcTemplate;
	
	@Override
	public Object saveComments(TComments comment, String type,String userId)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("user.userUnExist");
		
		if(comment==null){
			throw new ValidateException("news.unExist");
		}
		if(StringUtils.isBlank(comment.getComments())){
			throw new ValidateException("news.contentNull");
		}
		comment.setId(CreateID.getID());
		comment.setType(type);
		comment.setPublish_time(new Timestamp(new Date().getTime()));
		comment.setBlock_state("0");
		comment.setUserId(userId);
		
		TUserApp loginUser = findEntity(TUserApp.class, userId);
		if(loginUser==null){
			comment.setUserName("");
		}else{
			comment.setUserName(loginUser.getUserName());
		}
		
		// 保存
		if (saveEntity(comment) == null) {
			throw new ValidateException("common.illegalRequest");
		} else {
			return comment;
		}
	}
	@Override
	public boolean deleteComments(String commentId, String userId,String flag)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("user.userUnExist");
		
		TComments comment = null;
		if (StringUtils.isNotBlank(commentId)) {
			comment = findEntity(TComments.class, commentId);
			if (comment == null) {
				//throw new ValidateException("news.unExist");
				return true;
			}
		}
		if("app".equals(flag)){
			String comment_user_id = comment.getUserId();
			//只能删除自己的评论信息
			if(!comment_user_id.equals(userId)){
				throw new ValidateException("user.userIsNotRole");
			}
		}else{
			//如果登陆用户是PC系统管理员，则可以删除所有的评论信息
			TUser loginUser = findEntity(TUser.class, userId);
			if (loginUser == null) {
				throw new ValidateException("user.userUnExist");
			}
			
			String roleStr = loginUser.getRole();
			if(!roleStr.contains("Console Admin")){
				throw new ValidateException("user.userUnExist");
			}
		}
		TComments comments = null;
		if (StringUtils.isNotBlank(commentId)) {
			comments = findEntity(TComments.class, commentId);
			if (comments == null) {
				//throw new ValidateException("news.unExist");
				return true;
			}
		}
		return deleteEntity(comments);
	}
	@SuppressWarnings("unchecked")
	@Override
	public Object getCommentsById(Pager pager, String contentId, String type,String lastTime,String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("user.userUnExist");
		//设置评论
		List<TComments> commentList = new ArrayList<TComments>();
		pager.setPageNo(1);
		pager.setPageSize(5);
		String  commentSql="";
		if(StringUtils.isBlank(lastTime)){
			commentSql="select t.* from t_comments t where t.block_state='0' and t.type='"+type+"' and t.contentId='"+contentId+"' order by t.publish_time desc";
		}else{
			commentSql="select t.* from t_comments t where t.block_state='0' and t.type='"+type+"' and t.contentId='"+contentId+"' and t.publish_time<'"+DateUtil.timeStampToDate(lastTime)+"' order by t.publish_time desc";
		}
		
		commentList = (List<TComments>) this.getListBySql(pager, commentSql.toString(),TComments.class);
		if(commentList!=null && commentList.size()>0){
			for(int i=0;i<commentList.size();i++){
				String userid = commentList.get(i).getUserId();
				TUserApp loginUser = findEntity(TUserApp.class, userid);
				if(loginUser==null){
					commentList.get(i).setUserName("");
				}else{
					commentList.get(i).setUserName(loginUser.getUserName());
				}
				//登录人可以删除自己的评论，不能删除其他人的
				if(userid.equals(userId)){
					commentList.get(i).setCanDelete(true);
				}else{
					commentList.get(i).setCanDelete(false);
				}
				String pubDate = StringUtil.toString(commentList.get(i).getPublish_time());
				commentList.get(i).setPubDate(pubDate.substring(0, pubDate.length()-2));
			}
		}
		return commentList;
	}
	
	public Integer getCommentsAmount(String contentId, String type){
		//设置评论数量   Add by Bing 2015-07-07  
		Integer num=0;
		String likeSql="";
		if(StringUtils.isBlank(type)){
			likeSql="select count(*) num  from t_comments t where t.block_state='0' and t.contentId='"+contentId+"' order by t.publish_time desc";
		}else{
			likeSql="select count(*) num  from t_comments t where t.block_state='0' and t.type='"+type+"' and t.contentId='"+contentId+"' order by t.publish_time desc";
		}
		
		List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
		if(listMapLike!=null && listMapLike.size()>0){
			num  = StringUtil.toInteger(listMapLike.get(0).get("num"));
		}else{
			num=0;
		}
		return num;
	}
	@SuppressWarnings("unchecked")
	@Override
	public Object getAllCommentsById(String contentId, String type,String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 分割tag标签
		TUser loginUser = findEntity(TUser.class, userId);
		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		//设置评论  Add by Bing 2015-08-14  PC端查询所有评论
		List<TComments> commentList = new ArrayList<TComments>();
		String  commentSql="";
		if(StringUtils.isBlank(type)){
			commentSql="select t.* from t_comments t where t.contentId='"+contentId+"' order by t.publish_time desc";
		}else{
			commentSql="select t.* from t_comments t where t.type='"+type+"' and t.contentId='"+contentId+"' order by t.publish_time desc";
		}
				
		commentList = (List<TComments>) this.getListBySql(commentSql.toString(),TComments.class);
		if(commentList!=null && commentList.size()>0){
			for(int i=0;i<commentList.size();i++){
				String userid = commentList.get(i).getUserId();
				TUserApp appuser = findEntity(TUserApp.class, userid);
				if(appuser==null){
					commentList.get(i).setUserName("");
				}else{
					commentList.get(i).setUserName(appuser.getUserName());
				}
				if (!"reviewer".equals(loginUser.getUserType())) {
					commentList.get(i).setCanDelete(false);
				}else{
					commentList.get(i).setCanDelete(true);
				}
			}
		}
		return commentList;
	}
	@Override
	public Integer getAllCommentsAmount(String contentId, String type) {
		//设置评论数量   Add by Bing 2015-08-14  PC端查询所有评论数量
		Integer num=0;
		String likeSql="";
		if(StringUtils.isBlank(type)){
			likeSql="select count(*) num  from t_comments t where t.contentId='"+contentId+"' order by t.publish_time desc";
		}else{
			likeSql="select count(*) num  from t_comments t where t.type='"+type+"' and t.contentId='"+contentId+"' order by t.publish_time desc";
		}
				
		List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
		if(listMapLike!=null && listMapLike.size()>0){
			num  = StringUtil.toInteger(listMapLike.get(0).get("num"));
		}else{
			num=0;
		}
		return num;
	}
	@Override
	public Object saveBlockComments(String commentId,String userId) throws Exception{
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 分割tag标签
		TUser loginUser = findEntity(TUser.class, userId);
		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		TComments comments = null;
		if (StringUtils.isNotBlank(commentId)) {
			comments = findEntity(TComments.class, commentId);
			if (comments != null) {
				comments.setBlock_state("1");
				this.updateEntity(comments);
			}else{
				throw new ValidateException("news.unExist");
			}
		}
		return comments;
	}
	@Override
	public Object saveShowComments(String commentId, String userId)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 分割tag标签
		TUser loginUser = findEntity(TUser.class, userId);
		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		TComments comments = null;
		if (StringUtils.isNotBlank(commentId)) {
			comments = findEntity(TComments.class, commentId);
			if (comments != null) {
				comments.setBlock_state("0");
				this.updateEntity(comments);
			}else{
				throw new ValidateException("news.unExist");
			}
		}
		return comments;
	}
}
